import cv2
import numpy as np
import face_recognition
import os
from datetime import datetime


path = 'ImagesBasic'  # 人像存储位置
images = []
className = []
myList = os.listdir(path)  # 返回指定文件目录下的列表，这里返回的是人像图片
print(myList)

for cl in myList:  # 获取每张人像的名称
    curImg = cv2.imread(f'{path}/{cl}')
    images.append(curImg)
    className.append(os.path.splitext(cl)[0])
print(className)


def findEncodings(images):  # 获取所有存储的人像编码
    encodeList = []
    for img in images:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        encode = face_recognition.face_encodings(img)[0]
        encodeList.append(encode)
    return encodeList


def markAttendance(name):  # 打卡，生成记录
    with open('Attendance.csv', 'r+') as f:
        myDatalist = f.readlines()  # 读取文件中所有的行
        nameList = []
        for line in myDatalist:
            entry = line.split(',')
            nameList.append(entry[0])
        if name not in nameList:
            now = datetime.now()
            dtString = now.strftime('%H:%M:%S')  # 将日期时间格式化成字符串
            f.writelines(f'\n{name},{dtString}')  # 将包含多个字符串的可迭代对象写入文件中，这里是记录人名


encodeListKnown = findEncodings(images)
print('encoding complete')
cap = cv2.VideoCapture(0)#打开摄像头

while True:
    success, img = cap.read()
    imgs = cv2.resize(img, (0, 0), None, 0.25, 0.25)  # 调整图片大小
    imgs = cv2.cvtColor(imgs, cv2.COLOR_BGR2RGB)

    faceCurFrame = face_recognition.face_locations(imgs)  # 获取人脸位置信息
    encodesCurFrame = face_recognition.face_encodings(imgs, faceCurFrame)  # 获取人脸编码

    for encodeFace, faceLoc in zip(encodesCurFrame, faceCurFrame):  # zip函数，连接成字典
        matches = face_recognition.compare_faces(encodeListKnown, encodeFace)  # 人脸匹配度
        faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)  # 欧式距离
        # print(faceDis)
        matchIndex = np.argmin(faceDis)  # 返回数组中小元素的索引
        if matches[matchIndex]:
            name = className[matchIndex].upper()
            print(name)
            y1, x2, y2, x1 = faceLoc  # 人脸位置
            y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 1)
            cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
            cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
            markAttendance(name)  # 记录人名

    cv2.imshow(str('Face_Detector'), img)

    if cv2.waitKey(1) & 0xff == 27:
        break

